import type { ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import { ProTable, ProCard, ProDescriptions } from '@ant-design/pro-components';
import { useState, useEffect } from 'react';
import EventEmitter from 'eventemitter3';
import { getDeviceDetail, queryPatrolRecords } from '../service';
import type { PatrolRecordTableItem } from '../types';
import DetailModal from './components/DetailModal';
import HoverPlateNumber from '@/components/HoverPlateNumber';
import LocationMapMini from './components/LocationMapMini';
import type { PatrolDeviceTableItem } from '@/pages/Devices/Patrol/types';
import { message, Tag } from 'antd';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { getOperatorByIccid, handleTime } from '@/utils/utils';

export const eventEmitter = new EventEmitter();
export default (props: { deviceSn: string }) => {
  const { deviceSn } = props;
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [currentPageSize, setCurrentPageSize] = useState<number>(5);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
  const [datasource, setDatasource] = useState<PatrolRecordTableItem[]>([]);
  const [currentData, setCurrentData] = useState<PatrolRecordTableItem>();
  const [deviceInfo, setDeviceInfo] = useState<PatrolDeviceTableItem | null>();
  const currentPageChange = (type: 'increase' | 'decrease') => {
    if (type === 'decrease') {
      if (currentPage <= 1) return;
      setCurrentPage(currentPage - 1);
    } else if (type === 'increase' && hasMore) {
      setCurrentPage(currentPage + 1);
    }
  };
  useEffect(() => {
    getDeviceDetail(deviceSn).then((res) => {
      if (res.success) {
        setDeviceInfo(res.data);
        return true;
      }
      message.error({ content: res.message, key: 'patrol_record_detail' });
      return false;
    });
  }, [deviceSn]);
  const columns: ProColumns<PatrolRecordTableItem>[] = [
    {
      dataIndex: '_id',
      hideInTable: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '任务ID',
      dataIndex: 'taskId',
      hideInSearch: true,
      hideInTable: true,
      hideInForm: true,
      ellipsis: true,
      width: 200,
    },
    {
      title: '路段名称',
      dataIndex: 'parkingLotName',
      align: 'center',
      hideInForm: true,
      width: 120,
    },
    {
      title: '泊位编号',
      dataIndex: 'parkingSpotId',
      align: 'center',
      hideInForm: true,
      width: 100,
    },
    {
      title: '车牌号',
      dataIndex: 'plateNumber',
      align: 'center',
      hideInForm: true,
      width: 100,
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      hideInForm: true,
      hideInTable: true,
      valueType: 'dateTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      hideInForm: true,
      hideInTable: true,
      valueType: 'dateTime',
    },
    {
      title: '车牌识别时间',
      dataIndex: 'plateNumberRecognitionTime',
      align: 'center',
      hideInSearch: true,
      hideInForm: true,
      valueType: 'dateTime',
      width: 180,
    },
    {
      title: '车牌置信度',
      dataIndex: 'plateNumberConfidence',
      align: 'center',
      hideInSearch: true,
      hideInForm: true,
      width: 100,
    },
    {
      title: '车牌颜色',
      dataIndex: 'plateNumberColor',
      align: 'center',
      hideInSearch: true,
      hideInForm: true,
      width: 100,
      valueEnum: {
        0: { text: '-' },
        1: { text: '蓝' },
        2: { text: '黄' },
        3: { text: '白' },
        4: { text: '黑' },
        5: { text: '绿' },
        6: { text: '黄绿' },
      },
    },
    {
      title: '车牌图片',
      dataIndex: 'plateImageUrl',
      align: 'center',
      hideInSearch: true,
      hideInForm: true,
      width: 100,
      render: (_, record) => (
        <HoverPlateNumber plateNumber={record.plateNumber} plateImageUrl={record.plateImageUrl} />
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      width: 100,
      render: (_, record) => [
        <a
          key={record._id}
          onClick={() => {
            setCurrentData(record);
            setDetailModalVisible(true);
          }}
        >
          查看图片
        </a>,
      ],
    },
  ];
  const desColumns: ProDescriptionsItemProps<PatrolDeviceTableItem>[] = [
    {
      title: '设备编号',
      dataIndex: 'deviceSn',
      render: () => deviceSn,
    },
    {
      title: '生产厂家',
      dataIndex: 'manufacturer',
      render: (_, record) => record?.manufacturer || <PlaceHolderCpn text="暂无数据" />,
    },
    {
      title: '设备型号',
      dataIndex: 'deviceModel',
      render: (_, record) => record?.deviceModel || <PlaceHolderCpn text="暂无数据" />,
    },

    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
    },

    {
      title: '流量卡运营商',
      dataIndex: 'iccid',
      render: (_, record) =>
        record?.iccid ? (
          <Tag>{getOperatorByIccid(record.iccid)}</Tag>
        ) : (
          <PlaceHolderCpn text="暂无数据" />
        ),
    },
    {
      title: '流量卡过期时间',
      valueType: 'date',
      dataIndex: 'iccidExpiredTime',
      render: (_, record) =>
        record?.iccidExpiredTime ? (
          handleTime(record.iccidExpiredTime, 'YYYY-MM-DD')
        ) : (
          <PlaceHolderCpn text="暂无数据" />
        ),
    },
    {
      title: '当前坐标',
      dataIndex: 'coordinate',
      render: (_, record) => {
        const longtiude = record?.coordinate ? `${record?.coordinate[0] || 0}` : '0';
        const latitude = record?.coordinate ? `${record?.coordinate[1] || 0}` : '0';
        return `${longtiude.slice(0, 12)}, ${latitude.slice(0, 12)}`;
      },
    },
    {
      title: '最新刷新时间',
      dataIndex: 'refreshTime',
      valueType: 'dateTime',
      render: (_, record) =>
        record?.refreshTime ? (
          handleTime(record.refreshTime, 'YYYY-MM-DD HH:mm:ss')
        ) : (
          <PlaceHolderCpn text="暂无数据" />
        ),
    },
  ];
  return (
    <>
      <ProCard gutter={8}>
        <ProCard
          bordered
          colSpan={{
            xs: '35%',
            sm: '35%',
            md: '35%',
            lg: '35%',
            xl: '35%',
          }}
        >
          <ProDescriptions
            size="small"
            columns={desColumns}
            column={1}
            dataSource={deviceInfo || undefined}
          />
        </ProCard>
        <ProCard bordered style={{ height: '100%' }} ghost>
          <LocationMapMini location={deviceInfo?.coordinate || [120.202633, 30.266603]} />
        </ProCard>
      </ProCard>
      <ProTable
        rowKey="_id"
        columns={columns}
        columnEmptyText="暂无数据"
        search={{
          filterType: 'light',
          labelWidth: 'auto',
        }}
        scroll={{ x: true, y: '40vh' }}
        style={{ whiteSpace: 'nowrap' }}
        pagination={{
          size: 'default',
          showQuickJumper: true,
          pageSize: currentPageSize,
          current: currentPage,
        }}
        debounceTime={300}
        request={async (params, sort) => {
          const res = await queryPatrolRecords(deviceSn, params, sort);
          setDatasource(res.data);
          setHasMore(res.total > currentPage * currentPageSize);
          if (detailModalVisible) {
            eventEmitter.emit('patrol_record', currentPageSize);
          }
          return res;
        }}
        onChange={(pagination) => {
          setCurrentPage(pagination.current!);
          setCurrentPageSize(pagination.pageSize!);
        }}
      />
      {detailModalVisible && currentData !== undefined && (
        <DetailModal
          visible={detailModalVisible}
          datasource={datasource}
          hasmore={hasMore}
          data={currentData}
          parentPage={currentPage}
          parentPageSize={currentPageSize}
          pageChange={currentPageChange}
          setUnvisible={() => setDetailModalVisible(false)}
        />
      )}
    </>
  );
};
